package com.iemes.controller.system;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iemes.annotation.SystemLog;
import com.iemes.controller.index.BaseController;
import com.iemes.entity.ResFormMap;
import com.iemes.entity.RoleFormMap;
import com.iemes.entity.UserFormMap;
import com.iemes.exception.BusinessException;
import com.iemes.mapper.ResourcesMapper;
import com.iemes.mapper.RoleMapper;
import com.iemes.service.system.RoleService;
import com.iemes.util.Common;
import com.iemes.util.DateUtils;
import com.iemes.entity.FormMap;
import com.iemes.util.ListUtils;
import com.iemes.util.ResponseHelp;
import com.iemes.util.ShiroSecurityHelper;
import com.iemes.util.TreeObject;
import com.iemes.util.TreeUtil;

/**
 * 
 * @author MDS
 * @version 2.0
 */
@Controller
@RequestMapping("/system/role/")
public class RoleController extends BaseController {
	
	@Inject
	private RoleMapper roleMapper;
	
	@Inject
	private ResourcesMapper resourcesMapper;
	
	@Inject
	private RoleService roleService;
	
	private Logger log = Logger.getLogger(this.getClass());

	@RequestMapping("list")
	public String listUI(Model model,HttpServletRequest request) throws Exception {
		getTabData(model);
		handlePageRes(model,request);
		return Common.BACKGROUND_PATH + "/system/role/role_manager";
	}
	
	private void getTabData(Model model) {
		UserFormMap userFormMap = new UserFormMap(); 
		userFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
		List<UserFormMap> listUserFormMap = roleMapper.findByNames(userFormMap);
		//ResFormMap resFormMap = getFormMap(ResFormMap.class);
		/*String order = " order by level asc";
		resFormMap.put("$orderby", order);
		List<ResFormMap> mps = roleMapper.findByNames(resFormMap);*/
		List<ResFormMap> mps = findByResByParentResId("0");
		List<TreeObject> list = new ArrayList<TreeObject>();
		for (ResFormMap map : mps) {
			TreeObject ts = new TreeObject();
			Common.flushObject(ts, map);
			list.add(ts);
		}
		TreeUtil treeUtil = new TreeUtil(); 
		List<TreeObject> ns = treeUtil.getChildTreeObjects(list, "0", "");
		
		model.addAttribute("resourceList", ns);
		model.addAttribute("noBindUserList", listUserFormMap);
		model.addAttribute("bindUserList", null);
	}
	
	/**
	 * 保存角色
	 * @param roleSelectGroups
	 * @return
	 */
	@ResponseBody
	@RequestMapping("saveRole")
	@SystemLog(module="系统管理",methods="角色管理-保存角色")		//凡需要处理业务逻辑的.都需要记录操作日志
	public String saveRole(String roleSelectGroups){
		RoleFormMap roleFormMap = getFormMap(RoleFormMap.class);
		roleFormMap.put("create_time", DateUtils.getStringDateTime());
		roleFormMap.put("create_user", ShiroSecurityHelper.getCurrentUsername());
		roleFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
		try {
			roleService.saveRole(roleFormMap);
		}catch(BusinessException e) {
			log.error(e.getMessage());
			return ResponseHelp.responseErrorText(e.getMessage());
		}
		return ResponseHelp.responseText();
	}

	
	/**
	 * 检索角色
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("queryRole")
	public String queryRole(Model model,HttpServletRequest request) {
		String role_key = request.getParameter("role_key");
		RoleFormMap roleFormMap = new RoleFormMap(); 
		roleFormMap.put("role_key", role_key);
		roleFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
		List<RoleFormMap> listRoleFormMap = null;
		try {
			listRoleFormMap = roleMapper.findByNames(roleFormMap);
			if (!ListUtils.isNotNull(listRoleFormMap)) {
				log.error("未检索到角色名为："+role_key.toUpperCase()+"的角色信息");
				getTabData(model);
				model.addAttribute("errorMessage", "未检索到角色名为："+role_key.toUpperCase()+"的角色信息");
				handlePageRes(model,request);
				return Common.BACKGROUND_PATH + "/system/role/role_manager";
			}
			roleFormMap = listRoleFormMap.get(0);
			model.addAttribute("role", roleFormMap);
			
			UserFormMap noBindUser = new UserFormMap();
			noBindUser.put("where", " WHERE id NOT IN (SELECT user_id FROM mds_user_role WHERE role_id = '"+roleFormMap.getStr("id")+"') and site_id ='"+ ShiroSecurityHelper.getSiteId() +"'");
			List<UserFormMap> noBindUserList = roleMapper.findByWhere(noBindUser);
			
			UserFormMap bindUser = new UserFormMap();
			bindUser.put("where", " WHERE id IN (SELECT user_id FROM mds_user_role WHERE role_id = '"+roleFormMap.getStr("id")+"') ");
			List<UserFormMap> bindUserList = roleMapper.findByWhere(bindUser);
			
			String id = roleFormMap.getStr("id");
			FormMap<String, String> map2 = new FormMap<String, String>();
			map2.put("roleId",id);
			map2.put("siteId", ShiroSecurityHelper.getSiteId());
			map2.put("userNo", ShiroSecurityHelper.getCurrentUsername());
			List<Map<String, Object>> mps = resourcesMapper.findResByRoleId(map2);
			List<TreeObject> list = new ArrayList<TreeObject>();
			for (Map<String, Object> map : mps) {
				TreeObject ts = new TreeObject();
				Common.flushObject(ts, map);
				list.add(ts);
			}
			TreeUtil treeUtil = new TreeUtil(); 
			List<TreeObject> ns = treeUtil.getChildTreeObjects(list, "0", "");
			
			model.addAttribute("resourceList", ns);
			model.addAttribute("noBindUserList", noBindUserList);
			model.addAttribute("bindUserList", bindUserList);
		}catch(Exception e) {
			log.error(e.getMessage());
			getTabData(model);
			model.addAttribute("errorMessage", e.getMessage());
			handlePageRes(model,request);
			return Common.BACKGROUND_PATH + "/system/role/role_manager";
		}
		model.addAttribute("successMessage", "检索成功");
		handlePageRes(model,request);
		return Common.BACKGROUND_PATH + "/system/role/role_manager";
	}
	
	
	/**
	 * 删除角色
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("delRole")
	public String delRole(Model model,HttpServletRequest request) {
		String roleId = request.getParameter("role_id");
		try {
			if (StringUtils.isEmpty(roleId)) {
				throw new BusinessException("操作失败，参数不能为空！");
			}
			roleService.delRole(roleId);
		}catch(BusinessException e) {
			log.error(e.getMessage());
			model.addAttribute("errorMessage", e.getMessage());
			getTabData(model);
			handlePageRes(model,request);
			return Common.BACKGROUND_PATH + "/system/role/role_manager";
		}
		getTabData(model);
		model.addAttribute("successMessage", "删除角色信息成功");
		handlePageRes(model,request);
		return Common.BACKGROUND_PATH + "/system/role/role_manager";
	}
}